<?php

/**
 * 获得所有扩展分类属于指定分类的所有商品ID
 *
 * @access  public
 * @param   string $cat_id     分类查询字符串
 * @return  string
 */
function get_extension_goods($cats)
{
    $extension_goods_array = '';
    $sql = 'SELECT goods_id FROM ' . $GLOBALS['ecs']->table('goods_cat') . " AS g WHERE $cats";
    $extension_goods_array = $GLOBALS['db']->getCol($sql);
    return db_create_in($extension_goods_array, 'g.goods_id');   //出处：lib_commond.php
}

/**
 * 判断某个商品是否正在特价促销期
 *
 * @access  public
 * @param   float   $price      促销价格
 * @param   string  $start      促销开始日期
 * @param   string  $end        促销结束日期
 * @return  float   如果还在促销期则返回促销价，否则返回0
 */
function bargain_price($price, $start, $end)
{
    if ($price == 0)
    {
        return 0;
    }
    else
    {
        $time = gmtime();
        if ($time >= $start && $time <= $end)
        {
            return $price;
        }
        else
        {
            return 0;
        }
    }
}

/**
 * 获得促销商品
 *
 * @access  public
 * @return  array
 */
function get_promote_goods($cats = '',$num=null)
{
    $time = gmtime();

    $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style,g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_thumb, g.goods_img, g.shop_price ' .
            'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .  
            'WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ' .
            " AND g.is_promote = 1 AND promote_start_date <= '$time' AND promote_end_date >= '$time' ";

    $sql .= ' ORDER BY g.promote_end_date ASC';
    $sql .= " LIMIT $num ";
    $result = $GLOBALS['db']->getAll($sql);

    $goods = array();
    foreach ($result AS $idx => $row)
    {
        if ($row['promote_price'] > 0)
        {
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);

            $goods[$idx]['promotePrice'] =$promote_price;
        }
        else
        {
            $goods[$idx]['promotePrice'] = '';
        }

        $remain = getdate($row['promote_end_date']-time());
        
        $goods[$idx]['id']           = $row['goods_id'];
        $goods[$idx]['name']         = urlencode($row['goods_name']);
        $goods[$idx]['remain']['day']= $remain['mday']-1;
        $goods[$idx]['remain']['hour']= $remain['hours'];
        $goods[$idx]['remain']['minute']= $remain['minutes'];
        $goods[$idx]['remain']['second']= $remain['seconds'];
        $goods[$idx]['marketPrice'] = price_format(sprintf('%.1f',($row['shop_price'])*1.2))    ;
        $goods[$idx]['picture']        = urlencode($_SERVER['HTTP_HOST'] . '/' . $row['goods_thumb']);  
    }

    return $goods;
}


/**
 * 获得商品的详细信息
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  void
 */
function get_goods_info($goods_id)
{
    $time = gmtime();
    $sql = 'SELECT g.*, r.comment_rank, (gs.goods_number-IF(ca.goods_number,ca.goods_number,0)) AS goods_number, c.measure_unit, b.brand_id, b.brand_name AS goods_brand ' . 
            'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . 
            'LEFT JOIN ' . $GLOBALS['ecs']->table('category') . ' AS c ' . 
                "ON g.cat_id = c.cat_id " . 
            'LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ' . 
                "ON g.brand_id = b.brand_id " . 
            'LEFT JOIN ' . $GLOBALS['ecs']->table('comment') . ' AS r ' . 
                "ON r.goods_id = g.goods_id AND r.parent_id = 0 AND r.status = 1 " . 
            'LEFT JOIN ' . $GLOBALS['ecs']->table('goods_stock') . ' AS gs ' . 
                "ON gs.goods_id = g.goods_id AND gs.goods_attr_id = 0 " .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('cart') . ' AS ca ' . 
                "ON ca.goods_id = g.goods_id AND ca.goods_attr_id = 0 " .
            "WHERE g.goods_id = '$goods_id' AND g.is_delete = 0 " .
            "GROUP BY g.goods_id";

    $row = $GLOBALS['db']->getRow($sql);

    if ($row !== false)
    {
        /* 用户评论级别取整 */
        $row['comment_rank']  = ceil($row['comment_rank']) == 0 ? 5 : ceil($row['comment_rank']);

        /* 获得商品的销售价格 */
        $row['market_price']        = $row['market_price'] > 0 ? price_format($row['market_price']) : price_format(sprintf('%.1f',($row['shop_price'])*1.2));
        $row['shop_price']          = price_format($row['shop_price']);

        /* 修正促销价格 */
        if ($row['promote_price'] > 0)
        {
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
        }
        else
        {
            $promote_price = 0;
        }


        $row['promote_price_org'] =  $promote_price;
        $row['promote_price'] =  price_format($promote_price);


        /* 修正上架时间显示 */
        $row['add_time']      = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']);

        /* 促销时间倒计时 */
        $time = gmtime();
        if ($time >= $row['promote_start_date'] && $time <= $row['promote_end_date'])
        {
             $row['gmt_end_time']  = $row['promote_end_date'];
        }
        else
        {
            $row['gmt_end_time'] = 0;
        }
       
        /* 显示商品库存数量 */
        $row['goods_number']  = intval($row['goods_number']);

        /* 修正商品图片 */
        $row['goods_img']   = $row['goods_img'];
        $row['goods_thumb'] = $row['goods_thumb'];
        return $row;
    }
    else
    {
        return false;
    }
}

/**
 * 获得商品的属性和规格
 *
 * @access  public
 * @param   integer $goods_id
 * @return  array
 */
function get_goods_properties($goods_id)
{
    /* 对属性进行重新排序和分组 */
    $sql = "SELECT attr_group ".
            "FROM " . $GLOBALS['ecs']->table('goods_type') . " AS gt, " . $GLOBALS['ecs']->table('goods') . " AS g ".
            "WHERE g.goods_id='$goods_id' AND gt.cat_id=g.goods_type";
    $grp = $GLOBALS['db']->getOne($sql);

    if (!empty($grp))
    {
        $groups = explode("\n", strtr($grp, "\r", ''));
    }

    /* 获得商品的规格 */
    $sql = "SELECT a.attr_id, a.attr_name, a.attr_group, a.is_linked, a.attr_type, ".
                "g.goods_attr_id, g.attr_sku, g.attr_value, g.bg_code, g.font_code, g.attr_price, gs.goods_number " .
            'FROM ' . $GLOBALS['ecs']->table('goods_attr') . ' AS g ' .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('attribute') . ' AS a ON a.attr_id = g.attr_id ' .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('goods_stock') . ' AS gs ON g.goods_id = gs.goods_id AND g.attr_sku = gs.goods_sku AND gs.area_id = ' .$_SESSION['area_id'] .' '.
            "WHERE g.goods_id = '$goods_id' " .
            'ORDER BY a.sort_order, g.sort, g.goods_attr_id';
            
    $res = $GLOBALS['db']->getAll($sql);

    $arr['pro'] = array();     // 属性
    $arr['spe'] = array();     // 规格
    $arr['lnk'] = array();     // 关联的属性

    foreach ($res AS $row)
    {
        $row['attr_value'] = str_replace("\n", '<br />', $row['attr_value']);

        if ($row['attr_type'] == 0)
        {
            $group = (isset($groups[$row['attr_group']])) ? $groups[$row['attr_group']] : $GLOBALS['_LANG']['goods_attr'];

            $arr['pro'][$group][$row['attr_id']]['name']  = $row['attr_name'];
            $arr['pro'][$group][$row['attr_id']]['value'] = $row['attr_value'];
        }
        else
        {
            $arr['spe'][$row['attr_id']]['attr_type'] = $row['attr_type'];
            $arr['spe'][$row['attr_id']]['name']     = $row['attr_name'];
            $arr['spe'][$row['attr_id']]['values'][] = array(
                                                        'label'        => $row['attr_value'],
                                                        'price'        => $row['attr_price'],
                                                        'format_price' => price_format(abs($row['attr_price']), false),
                                                        'id'           => $row['goods_attr_id'],
                                                        'goods_attr_sku'           => $row['attr_sku'],
                                                        'bg_code'           => $row['bg_code'],
                                                        'goods_number'           => $row['goods_number'],
                                                        'font_code'           => $row['font_code']);
        }

        if ($row['is_linked'] == 1)
        {
            /* 如果该属性需要关联，先保存下来 */
            $arr['lnk'][$row['attr_id']]['name']  = $row['attr_name'];
            $arr['lnk'][$row['attr_id']]['value'] = $row['attr_value'];
        }
    }
    
    // 颜色定义start    
    foreach($arr['spe'] AS $key=>$value){
        if($value['name']=="颜色"){
            foreach($value['values'] AS $k=>$v){
                $arr['spe'][$key]['values'][$k]['color']=$v['bg_code'];
                $arr['spe'][$key]['values'][$k]['id']=$v['id'];
                $arr['spe'][$key]['values'][$k]['text_color']= $v['font_code']=='#000000'?1:0;
            }
        }
    }
    unset($arr['spe'][3]);
    
    return $arr;
}

/**
 * 获得指定商品的相册
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_goods_gallery($goods_id,$num)
{
    $sql = 'SELECT img_id, img_url, img_original, thumb_url, img_desc' .
        ' FROM ' . $GLOBALS['ecs']->table('goods_gallery') .
        " WHERE goods_id = '$goods_id' ORDER BY img_desc ASC LIMIT " . ($num?$num:$GLOBALS['_CFG']['goods_gallery_number']);
    $row = $GLOBALS['db']->getAll($sql);
    /* 格式化相册图片路径 */
    foreach($row as $key => $gallery_img)
    {
        $row[$key]['img_url'] = get_image_path($goods_id, $gallery_img['img_url'], false, 'gallery');
        $row[$key]['thumb_url'] = get_image_path($goods_id, $gallery_img['thumb_url'], true, 'gallery');
    }
    return $row;
}


?>